package com.air.admin.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.air.admin.dao.AdminPrivilegeDao;
import com.air.admin.dao.AdminRoleDao;
import com.air.admin.dao.BasicAdminInfoDao;
import com.air.admin.mo.AdminPrivilege;
import com.air.admin.mo.AdminRole;
import com.air.admin.mo.BasicAdminInfo;
import com.air.admin.service.IAdminRoleService;
import com.air.admin.service.IBasicAdminInfoService;
import com.air.admin.vo.AdminInfoQueryRequestVO;
import com.air.common.exception.DuplicateEntityException;
import com.air.common.exception.NoSuchUserException;
import com.air.common.exception.WrongPasswordException;
import com.air.common.service.imp.BaseServiceImp;
import com.air.common.util.BasicDBDictionary;
import com.air.common.util.CommonUtil;
import com.air.common.util.QueryCondition;
import com.air.common.util.QueryExpression;
import com.air.common.vo.PageResultListVO;

public class BasicAdminInfoServiceImp extends BaseServiceImp implements
		IBasicAdminInfoService,InitializingBean {
	
	private final String simpleModeQueryStringTemplate="LOGIN_NAME like '%{queryString}%' " +
							"or ROLES like '%{queryString}%'";

	
	@Autowired
	IAdminRoleService adminRoleService;
	
	@Autowired
	BasicAdminInfoDao basicAdminInfoMapper;
	
	@Autowired
	AdminRoleDao adminRoleMapper;
	
	@Autowired
	AdminPrivilegeDao adminPrivilegeMapper;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		this.baseDao = basicAdminInfoMapper;
	}
	
	@Override
	public BasicAdminInfo validateAdmin(String loginName, String password)
			throws Exception {
		
		QueryCondition condition = new QueryCondition();
		condition.addQueryCondition("loginName", loginName, QueryExpression.EQUALS);
		condition.addQueryCondition("status", BasicDBDictionary._common_status_available, QueryExpression.EQUALS);
		
		List<BasicAdminInfo> result=baseDao.queryByCondition(condition);
		if (result==null||result.size()==0){
			throw new NoSuchUserException();
		}
		if (result.size()>1){
			logger.error("FOUND "+result.size()+" Admin_User Entities (login_name="+loginName+")");
			throw new DuplicateEntityException();
		}
		
		BasicAdminInfo adminInfo = result.get(0);
		
		if (!adminInfo.getPassword().equals(CommonUtil.getMD5Str(password))){
			throw new WrongPasswordException();
		}
		
		return adminInfo;
	}

	@Override
	public List<AdminPrivilege> getPrivileges(BasicAdminInfo adminInfo) {
		
		List<AdminRole> roleList = getRoles(adminInfo);
		List<AdminPrivilege> privilegeList = new ArrayList<AdminPrivilege>();
		for(AdminRole role:roleList){
			List<AdminPrivilege> privilegesInRole = adminRoleService.getPrivilege(role);
			for(AdminPrivilege aPrivilege:privilegesInRole){
				if (!privilegeList.contains(aPrivilege)){
					privilegeList.add(aPrivilege);
				}
			}
		}
		
		return privilegeList;
	}
	
	
	
	
	@Override
	public List<AdminRole> getRoles(BasicAdminInfo adminInfo) {
		
		List<AdminRole> roles = new ArrayList<AdminRole>();
		
		if (adminInfo.getRoles() == null){
			return roles;
		}
		
		String[] rolesCode = adminInfo.getRoles().split(",");
		for(String roleCode:rolesCode){
			AdminRole role =  adminRoleMapper.selectByCode(roleCode);
			if (role!=null){
				roles.add(role);
			}
		}
		
		return roles;
	}

	@Override
	public boolean hasRelativeAdmin(List<String> roleCodeList) {
		
		for(String roleCode:roleCodeList){
			QueryCondition condition = new QueryCondition();
			condition.addQueryCondition("roles", roleCode, QueryExpression.LIKE);
			List<BasicAdminInfo> adminInfos =  this.queryByCondition(condition);
			if(adminInfos!=null&&adminInfos.size()>0){
				return true;
			}
		}
		
		
		return false;
	}

	@Override
	public PageResultListVO queryInAdvanceMode(QueryCondition condition,
			Integer pageNum, Integer pageLimit,
			AdminInfoQueryRequestVO queryRequestVO) throws Exception {
		
		if (queryRequestVO.getLoginName().length()>0){
			condition.addQueryCondition("loginName", queryRequestVO.getLoginName(), QueryExpression.LIKE);
		}
		if (queryRequestVO.getRoles().length()>0){
			condition.addQueryCondition("roles", queryRequestVO.getRoles(), QueryExpression.LIKE);
		}
		
		return queryByCondition(condition, pageNum, pageLimit);
	}

	@Override
	public PageResultListVO queryInSimpleMode(QueryCondition condition,
			Integer pageNum, Integer pageLimit, String queryString)
			throws Exception {
		
		if (queryString!=null&&queryString.trim().length()>0){
			queryString = queryString.toUpperCase();
			String simpleModeQueryCondition = simpleModeQueryStringTemplate.replace("{queryString}", queryString);
			condition.addManualCondition(simpleModeQueryCondition);
		}
		
		return this.queryByCondition(condition, pageNum, pageLimit);
	}

	@Override
	public BasicAdminInfo registerAdmin(BasicAdminInfo adminInfo)  throws Exception
	 {
		
		
		adminInfo.setStatus(BasicDBDictionary._common_status_available);
		adminInfo.setPassword(CommonUtil.getMD5Str(adminInfo.getPassword()));
		return this.insert(adminInfo);
	}
	
		
	
}
